package com.tl.commonlibrary.ui;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.tl.commonlibrary.BuildConfig;
import com.tl.commonlibrary.R;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.widget.LoadingView;
import com.tl.commonlibrary.ui.widget.NetErrorView;
import com.tl.commonlibrary.ui.widget.NoDataView;
import com.tl.commonlibrary.ui.widget.ProgressDialog;
import com.tl.commonlibrary.ui.widget.TitleBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;


/**
 */
public abstract class BaseFragmentActivity extends AppCompatActivity implements OnClickListener, BaseFragment.OnFragmentTriggerListener, NetErrorView.OnNetErrorClickListener, NoDataView.OnNoDataClickListener {
    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    protected String tag = null;
    protected Context context = null;
    protected ProgressDialog dialog;
    protected NetErrorView netErrorView;
    protected LoadingView loadingView;
    protected NoDataView noDataView;

    private TitleBar titleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.context = this;
        super.onCreate(savedInstanceState);
        tag = this.getClass().getSimpleName();
        ActivityStack.get().onCreate(this);
        commInit();
    }

    public TitleBar getTitleBar() {
        if (titleBar == null) {
            titleBar = (TitleBar) findViewById(R.id.actionBar);
        }
        return titleBar;
    }

    /**
     * 使用之前xml中是否<include layout="@layout/action_bar" />
     *
     * @param resId
     */
    public void setTitle(int resId) {
        if (getTitleBar() != null) {
            titleBar.setTitle(resId);
        }
    }

    public void setTitle(String text) {
        if (getTitleBar() != null) {
            titleBar.setTitle(text);
        }
    }

    public void setTitleBackground(int resId) {
        if (getTitleBar() != null) {
            titleBar.setBackgroundResource(resId);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
        ActivityStack.get().onStarted(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        ActivityStack.get().onStop(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            if (dialog.isShowing()) {
                dismissProgressDialog();
            }
            dialog = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        ActivityStack.get().onDestroy(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void commInit() {
        //每次打开一个界面都需要重新初始化全局变量，防止进程终止重新初始化成默认值
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏//当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
////            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        }
        initStatusBar();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
//            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
//            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
//        }

    }


    /**
     * 初始化手机状态栏，保持状态栏和手机app的颜色主题一致
     */
    private void initStatusBar() {
        //将手机状态栏透明化，
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        } else {

        }
    }


    /**
     * activity在数据上需要的几种UI显示
     * 1.{@link ProgressDialog} Dialog方式，浮层之上，显示正在加载数据
     * 2.{@link LoadingView}view方式，与UI在同一层，显示正在加载数据
     * 3.{@link NetErrorView}view方式，与UI在同一层，加载失败无网络的情况需要用到
     * 4.{@link Toast} 浮层方式，显示其他消息提示
     */

    public void showProgressDialog() {
        showProgressDialog(true);
    }

    public void showProgressDialog(boolean cancelable) {
        dismissAll();
        if (dialog == null) {
            dialog = new ProgressDialog(context);
        }
        dialog.setCancelable(cancelable);
        dialog.show();
    }

    public void showProgressDialog(String message) {
        showProgressDialog(message, true);
    }

    public void showProgressDialog(String message, boolean cancelable) {
        dismissAll();
        if (dialog == null) {
            dialog = new ProgressDialog(context, message);
        } else {
            dialog.setMessage(message);
        }
        dialog.setCancelable(cancelable);
        dialog.show();
    }

    public void showProgressDialog(int messageResId) {
        showProgressDialog(messageResId, true);
    }

    public void showProgressDialog(int messageResId, boolean cancelable) {
        dismissAll();
        if (dialog == null) {
            dialog = new ProgressDialog(context, messageResId);
        } else {
            dialog.setMessage(messageResId);
        }
        dialog.setCancelable(cancelable);
        dialog.show();
    }

    public void dismissProgressDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
        dialog = null;
    }

    public void setProgressDialogMessage(String message) {
        if (dialog != null) {
            dialog.setMessage(message);
        }
    }

    public void setProgressDialogMessage(int messageResId) {
        if (dialog != null) {
            dialog.setMessage(messageResId);
        }
    }

    public void setCancelableProgressDailog(boolean flag) {
        if (dialog != null) {
            dialog.setCancelable(flag);
        }
    }

    public boolean isDialogShowing() {
        return dialog != null && dialog.isShowing();
    }


    public void showLoading() {
        showLoading("正在加载中...");
    }

    public void showLoading(int messageResId) {
        dismissAll();
        if (loadingView == null) {
            loadingView = new LoadingView(context);
        }
        loadingView.setText(messageResId);
        if (loadingView.getParent() == null) {
            ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
            viewGroup.addView(loadingView);
        }
        loadingView.setVisibility(View.VISIBLE);
    }

    /**
     * 加载UI
     *
     * @param message
     */
    public void showLoading(String message) {
        dismissAll();
        if (loadingView == null) {
            loadingView = new LoadingView(context);
        }
        loadingView.setText(message);
        if (loadingView.getParent() == null) {
            ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
            viewGroup.addView(loadingView);
        }
        loadingView.setVisibility(View.VISIBLE);
    }

    public void dismissLoading() {
        if (loadingView != null) {
            loadingView.setVisibility(View.GONE);
            if (loadingView.getParent() != null) {
                ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
                viewGroup.removeView(loadingView);
            }
            loadingView = null;
        }
    }

    public boolean isLoadingShowing() {
        return loadingView != null && loadingView.getParent() != null && loadingView.getVisibility() == View.VISIBLE;
    }


    public void showNetError() {
        dismissAll();
        if (netErrorView == null) {
            netErrorView = new NetErrorView(context);
            netErrorView.setOnLoadFailedClickListener(this);
        }
        if (netErrorView.getParent() == null) {
            ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
            viewGroup.addView(netErrorView);
        }
        noDataView.setVisibility(View.VISIBLE);
    }

    public void showNoDataView() {
        showNoDataView(null);
    }

    public void showNoDataView(String message) {
        dismissAll();
        if (noDataView == null) {
            noDataView = new NoDataView(context);
            noDataView.setNoDataClickListener(this);
        }
        if (noDataView.getParent() == null) {
            ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
            viewGroup.addView(noDataView);
        }
        if (!TextUtils.isEmpty(message)) {
            noDataView.setText(message);
        }
        noDataView.setVisibility(View.VISIBLE);
    }

    /**
     * 加载失败UI
     */
    public void dismissNetError() {
        if (netErrorView != null) {
            netErrorView.setVisibility(View.GONE);
            if (netErrorView.getParent() != null) {
                ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
                viewGroup.removeView(netErrorView);
            }
            netErrorView = null;
        }
    }

    /**
     *
     */
    public void dismissNoData() {
        if (noDataView != null) {
            noDataView.setVisibility(View.GONE);
            if (noDataView.getParent() != null) {
                ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
                viewGroup.removeView(noDataView);
            }
            noDataView = null;
        }
    }

    public boolean isNerErrorShowing() {
        return netErrorView != null && netErrorView.getParent() != null && netErrorView.getVisibility() == View.VISIBLE;
    }

    public boolean isNoDataShowing() {
        return noDataView != null && noDataView.getParent() != null && noDataView.getVisibility() == View.VISIBLE;
    }

    /**
     * @param resId
     * @deprecated see {@link UIUtils#showToast(int)}
     */
    public void showToast(int resId) {
        showToast(resId, Toast.LENGTH_SHORT);
    }

    /**
     * @deprecated see {@link UIUtils#showToast(String)}
     */
    public void showToast(String text) {
        showToast(text, Toast.LENGTH_SHORT);
    }

    /**
     * @deprecated see {@link UIUtils#showToast(String, int)}
     */
    public void showToast(String text, int duration) {
        UIUtils.showToast(text, duration);
    }

    /**
     * @deprecated see {@link UIUtils#showToast(int, int)}
     */
    public void showToast(int resId, int duration) {
        UIUtils.showToast(resId, duration);
    }

    public void println(String content) {
        if (BuildConfig.DEBUG) {
            System.out.println(tag + "==>" + content);
        }
    }

    /**
     * 关闭所有不需要显示的UI
     */
    public void dismissAll() {
        dismissNetError();
        dismissLoading();
        dismissProgressDialog();
        dismissNoData();
    }

    /**
     * 重载该方法 实现 点击加载失败图标 的点击事件
     */
    @Override
    public void onNetErrorClicked() {
    }

    @Override
    public void onNoDataClicked() {
    }

    /**
     * 淡入淡出效果
     *
     * @param intent
     */
    public void startActivityFade(Intent intent) {
        startActivityOverridingPending(intent, android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 由左向右滑入的效果
     *
     * @param intent
     */
    public void startActivitySlide(Intent intent) {
        startActivityOverridingPending(intent, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    public void startActivityOverridingPending(Intent intent, int enterAmin, int exitAnim) {
        startActivity(intent);
        overridePendingTransition(enterAmin, exitAnim);
    }

    public void setActivityTransparent(float transparent) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = transparent;
        layoutParams.dimAmount = 1 - transparent;
        getWindow().setAttributes(layoutParams);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    /**
     * 隐藏键盘
     */
    public void hiddenKeyboard() {
        if (getCurrentFocus() != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void back() {
        onBackPressed();
    }

    //设置标的物分类
    public List<String> BDWType() {
        final ArrayList<String> li = new ArrayList<>();
        li.add("废有色");
        li.add("废塑料");
        li.add("废钢铁");
        li.add("废纸");
        li.add("废橡胶");
        li.add("机械设备");
        li.add("废电子电器");
        return li;

    }

}

